package com.zhuozhengsoft.springbootpageoffice.controller;

import com.zhuozhengsoft.pageoffice.FileSaver;
import com.zhuozhengsoft.pageoffice.OpenModeType;
import com.zhuozhengsoft.pageoffice.PageOfficeCtrl;
import com.zhuozhengsoft.springbootpageoffice.entity.Doc;
import com.zhuozhengsoft.springbootpageoffice.util.GetDirPathUtil;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/BingFa")
public class BingFaController {

    //获取doc目录的磁盘路径
    private String dir = GetDirPathUtil.getDirPath() + "static/doc/";

    @RequestMapping(value = "/index")
    public ModelAndView showWord(HttpServletRequest request , Map<String, Object> map)throws SQLException, ClassNotFoundException, IOException {

        Class.forName("org.sqlite.JDBC");
        String strUrl = "jdbc:sqlite:"+ ResourceUtils.getURL("classpath:").getPath() + "static/demodata/BingFa.db";
        Connection conn= DriverManager.getConnection(strUrl);
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("select * from doc order by id desc");
        List<Doc> docList = new ArrayList<Doc>();
        while (rs.next()) {
            String str0 = rs.getString(1);
            if (str0 != null && str0.length() > 0) {
                Doc doc = new Doc();
                doc.setFileName(rs.getString(3));
                doc.setId(Integer.parseInt(rs.getString(1)));
                docList.add(doc);
            }
        }
        rs.close();
        stmt.close();
        conn.close();
        map.put("docList", docList);
        ModelAndView mv = new ModelAndView("BingFa/index");
        return mv;
    }


    @RequestMapping(value = "/detectCurrentEditor")
    public void detectCurrentEditor(HttpServletRequest request , HttpServletResponse response)throws SQLException, ClassNotFoundException, IOException {

        String id = request.getParameter("id");
        String editor = "";

        Class.forName("org.sqlite.JDBC");
        String strUrl = "jdbc:sqlite:"+ ResourceUtils.getURL("classpath:").getPath() + "static/demodata/BingFa.db";
        Connection conn=DriverManager.getConnection(strUrl);
        Statement stmt = conn.createStatement();
        ResultSet	rs = stmt.executeQuery("select * from doc where id="+id);
        if(rs.next()){
            editor = rs.getString(4);
        }
        rs.close();
        stmt.close();
        conn.close();

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print("{\"editor\":\""+ editor +"\"}");
    }

    @RequestMapping(value = "/clearCurrentEditor")
    public void clearCurrentEditor(HttpServletRequest request , HttpServletResponse response)throws SQLException, ClassNotFoundException, IOException {
        String id = request.getParameter("id");

        Class.forName("org.sqlite.JDBC");
        String strUrl = "jdbc:sqlite:"+ ResourceUtils.getURL("classpath:").getPath() + "static/demodata/BingFa.db";
        Connection conn=DriverManager.getConnection(strUrl);
        Statement stmt2 = conn.createStatement();
        stmt2.executeUpdate("Update doc set Editor='' where id="+id);
        stmt2.close();
        conn.close();

        response.setContentType("application/json");
        response.getWriter().print("{\"msg\":\"ok\"}");
    }

    @RequestMapping(value = "/word")
    public ModelAndView word(HttpServletRequest request , Map<String, Object> map)throws SQLException, ClassNotFoundException, IOException {

        String id = request.getParameter("id");
        String user = request.getParameter("user");

        String fileName = "";
        String subject = "";
        String userName = URLDecoder.decode(user, "UTF-8");;

        Class.forName("org.sqlite.JDBC");
        String strUrl = "jdbc:sqlite:"+ ResourceUtils.getURL("classpath:").getPath() + "static/demodata/BingFa.db";
        Connection conn=DriverManager.getConnection(strUrl);
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("select * from doc where id="+id);
        if(rs.next()){
            fileName = rs.getString(2);
            subject = rs.getString(3);
        }
        rs.close();
        stmt.close();

        // 文档表中的Editor字段用来记录打开当前文件的用户
        Statement stmt2 = conn.createStatement();
        stmt2.executeUpdate("Update doc set Editor='"+ userName +"' where id="+id);
        stmt2.close();
        conn.close();

        PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
        poCtrl.setCaption("当前用户：" + userName  + " | 模式：修订编辑 | 文档名称："+ subject );
        poCtrl.setSaveFilePage("savefile");
        poCtrl.webOpen("/doc/BingFa/" +fileName, OpenModeType.docRevisionOnly, userName);
        map.put("pageoffice", poCtrl.getHtml());
        map.put("subject",subject);
        ModelAndView mv = new ModelAndView("BingFa/Word");
        return mv;
    }

    @RequestMapping(value = "/word2")
    public ModelAndView word2(HttpServletRequest request , Map<String, Object> map)throws SQLException, ClassNotFoundException, IOException {
        String id = request.getParameter("id");
        String user = request.getParameter("user");

        String fileName = "";
        String subject = "";
        String userName = URLDecoder.decode(user, "UTF-8");;

        Class.forName("org.sqlite.JDBC");
        String strUrl = "jdbc:sqlite:"+ ResourceUtils.getURL("classpath:").getPath() + "static/demodata/BingFa.db";
        Connection conn=DriverManager.getConnection(strUrl);
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("select * from doc where id="+id);
        if(rs.next()){
            fileName = rs.getString(2);
            subject = rs.getString(3);
        }
        rs.close();
        stmt.close();

        PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
        poCtrl.setCaption("当前用户：" + userName + " | 模式：只读查看 | 文档名称："+ subject );
        poCtrl.webOpen("/doc/BingFa/" + fileName, OpenModeType.docReadOnly, userName);
        map.put("pageoffice", poCtrl.getHtml());
        map.put("subject",subject);
        ModelAndView mv = new ModelAndView("BingFa/Word2");
        return mv;
    }

    @RequestMapping(value = "/savefile")
    public void save(HttpServletRequest request , HttpServletResponse response)throws SQLException, ClassNotFoundException, IOException {

        FileSaver fs = new FileSaver(request, response);
        fs.saveToFile(dir + "BingFa/"+ fs.getFileName());
        fs.close();
    }
}
